package com.vipboot.framework.mybatisflex.core.listener;

import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.ReflectUtil;

import com.mybatisflex.annotation.InsertListener;
import com.vipboot.framework.core.exception.ServiceException;
import com.vipboot.framework.satoken.helper.LoginHelper;
import lombok.extern.slf4j.Slf4j;

import java.lang.reflect.Field;
import java.time.LocalDateTime;
import java.util.Date;

@Slf4j
public class EntityInsertListener implements InsertListener {

    @Override
    public void onInsert(Object entity) {
        try {
            if (EntityListenerManager.isDoInsertListener()) {
                log.info("进入全局插入数据监听器");
                Field createTimeField = ReflectUtil.getField(entity.getClass(), "createTime");
                if (ObjectUtil.isNotNull(createTimeField)) {
                    ReflectUtil.setFieldValue(entity, createTimeField, new Date());
                }
                Field updateTimeField = ReflectUtil.getField(entity.getClass(), "updateTime");
                if (ObjectUtil.isNotNull(updateTimeField)) {
                    ReflectUtil.setFieldValue(entity, updateTimeField, LocalDateTime.now());
                }
                Field createByField = ReflectUtil.getField(entity.getClass(), "createBy");
                if (ObjectUtil.isNotNull(createByField)) {
                    Long loginUserId = LoginHelper.getUserId();
//                    Long loginUserId = userContextProvider.getUserContext().getUserId();
                    ReflectUtil.setFieldValue(entity, createByField, loginUserId);
                }
                Field createDeptField = ReflectUtil.getField(entity.getClass(), "createDept");
                if (ObjectUtil.isNotNull(createDeptField)) {
                    Long loginDeptId = LoginHelper.getDeptId();
//                    Long loginDeptId = userContextProvider.getUserContext().getDeptId();
                    ReflectUtil.setFieldValue(entity, createDeptField, loginDeptId);
                }
            }
        } catch (Exception e) {
            throw new ServiceException("全局插入数据监听器注入异常 => " + e.getMessage());
        }
    }
}
